// 从detail.js中导入植物数据
const plantData = window.plantData || {};
const treatmentData = window.treatmentData || {};

// 页面加载时初始化
window.addEventListener('load', () => {
    loadTreatments();
});

// 加载保护措施列表
function loadTreatments() {
    const treatmentList = document.getElementById('treatmentList');
    let html = '';
    let hasData = false;
    
    Object.entries(treatmentData).forEach(([plantId, data]) => {
        const plantName = plantData[plantId]?.name || '未知植物';
        
        ['disease', 'pest', 'environment'].forEach(type => {
            const treatments = data[type] || [];
            treatments.forEach(treatment => {
                hasData = true;
                html += `
                    <div class="treatment-card">
                        <div class="treatment-header">
                            <h3>${plantName} - ${treatment.name}</h3>
                            <span class="treatment-type" data-type="${type}">${getTypeName(type)}</span>
                        </div>
                        <div class="treatment-content">
                            <p><strong>症状：</strong>${treatment.symptoms}</p>
                            <div class="treatment-solutions">
                                <strong>解决方案：</strong>
                                <ul>
                                    ${treatment.solutions.map(solution => `<li>${solution}</li>`).join('')}
                                </ul>
                            </div>
                        </div>
                        <div class="treatment-actions">
                            <button onclick="editTreatment('${plantId}', '${type}', '${treatment.name}')">
                                编辑
                            </button>
                            <button onclick="deleteTreatment('${plantId}', '${type}', '${treatment.name}')">
                                删除
                            </button>
                        </div>
                    </div>
                `;
            });
        });
    });
    
    treatmentList.innerHTML = hasData ? html : '<p class="no-data">暂无保护措施数据</p>';
}

// 获取问题类型的中文名称
function getTypeName(type) {
    const typeNames = {
        'disease': '病害',
        'pest': '虫害',
        'environment': '环境问题'
    };
    return typeNames[type] || type;
}

// 筛选保护措施
function filterTreatments() {
    loadTreatments();
}

// 打开添加新保护措施的弹窗
function addNewTreatment() {
    const modal = document.getElementById('treatmentModal');
    const form = document.getElementById('treatmentForm');
    form.reset();
    modal.style.display = 'block';
}

// 添加新的解决方案输入框
function addSolutionInput() {
    const solutionInputs = document.getElementById('solutionInputs');
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'solution-input';
    input.required = true;
    solutionInputs.insertBefore(input, solutionInputs.lastElementChild);
}

// 关闭弹窗
function closeModal() {
    const modal = document.getElementById('treatmentModal');
    modal.style.display = 'none';
}

// 编辑保护措施
function editTreatment(plantId, type, name) {
    const treatment = treatmentData[plantId][type].find(t => t.name === name);
    if (!treatment) return;

    const modal = document.getElementById('treatmentModal');
    const form = document.getElementById('treatmentForm');
    
    // 填充表单数据
    document.getElementById('plantSelect').value = plantId;
    document.getElementById('treatmentType').value = type;
    document.getElementById('treatmentName').value = name;
    document.getElementById('symptoms').value = treatment.symptoms;
    
    // 清除现有的解决方案输入框
    const solutionInputs = document.getElementById('solutionInputs');
    while (solutionInputs.children.length > 1) {
        solutionInputs.removeChild(solutionInputs.firstChild);
    }
    
    // 添加解决方案输入框
    treatment.solutions.forEach((solution, index) => {
        if (index === 0) {
            solutionInputs.firstElementChild.value = solution;
        } else {
            const input = document.createElement('input');
            input.type = 'text';
            input.className = 'solution-input';
            input.required = true;
            input.value = solution;
            solutionInputs.insertBefore(input, solutionInputs.lastElementChild);
        }
    });
    
    modal.style.display = 'block';
}

// 删除保护措施
function deleteTreatment(plantId, type, name) {
    if (!confirm('确定要删除这个保护措施吗？')) return;
    
    const treatments = treatmentData[plantId][type];
    const index = treatments.findIndex(t => t.name === name);
    if (index !== -1) {
        treatments.splice(index, 1);
        loadTreatments();
    }
}

// 处理表单提交
document.getElementById('treatmentForm').addEventListener('submit', (e) => {
    e.preventDefault();
    
    const plantId = document.getElementById('plantSelect').value;
    const type = document.getElementById('treatmentType').value;
    const name = document.getElementById('treatmentName').value;
    const symptoms = document.getElementById('symptoms').value;
    
    // 收集所有解决方案
    const solutions = Array.from(document.querySelectorAll('.solution-input'))
        .map(input => input.value)
        .filter(value => value.trim() !== '');
    
    // 创建或更新保护措施
    if (!treatmentData[plantId]) {
        treatmentData[plantId] = {};
    }
    if (!treatmentData[plantId][type]) {
        treatmentData[plantId][type] = [];
    }
    
    const existingIndex = treatmentData[plantId][type].findIndex(t => t.name === name);
    const treatmentItem = {
        name,
        symptoms,
        solutions
    };
    
    if (existingIndex !== -1) {
        treatmentData[plantId][type][existingIndex] = treatmentItem;
    } else {
        treatmentData[plantId][type].push(treatmentItem);
    }
    
    closeModal();
    loadTreatments();
});

// 显示文章详情
function showArticleDetail() {
    const modal = document.getElementById('articleModal');
    modal.style.display = 'block';
}

// 关闭文章详情
function closeArticleModal() {
    const modal = document.getElementById('articleModal');
    modal.style.display = 'none';
} 